package com.lss.a_hash;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lss
 * @description
 * @createDate 2024/11/26-8:59
 */
public class lc_128 {
    /**
     * 找到给定整数数组中最长连续序列的长度。
     *
     * @param nums 输入的整数数组
     * @return 最长连续序列的长度
     * @tag 补丁之神 hihihi
     */
    public static int longestConsecutive(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        if (nums.length == 1) {
            return 1;
        }
        Integer[] array = Arrays.stream(nums).boxed().toArray(Integer[]::new);
        List<Integer> list = Arrays.asList(array);
        Set<Integer> set = new HashSet<>(list);
        /**
         * 优雅
         */
        List<Integer> res = set.stream().sorted(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        }).toList();
        if (res.size() == 1) {
            return 1;
        }
        int max = -1;
        int left = 0;
        for (int i = 1; i < res.size(); i++) {
            if ((res.get(i) - res.get(i - 1)) != 1) {
                max = Math.max(max, (i - left));
                left = i;
                continue;
            }
            if (max == -1 && i == res.size() - 1) {
                return Math.max(max, (i - left + 1));
            }
            max = Math.max(max, (i - left + 1));
        }
        return max;
    }

    /**
     * good ||
     * @param nums
     * @return
     */
    public static int longestConsecutive1(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }

        HashSet<Integer> set = new HashSet<>();
        for (int num : nums) {
            set.add(num);
        }

        int longestStreak = 0;

        for (int num : set) {
            // 只有当 num-1 不在集合中时，才开始计算连续序列
            if (!set.contains(num - 1)) {
                int currentNum = num;
                int currentStreak = 1;

                while (set.contains(currentNum + 1)) {
                    currentNum += 1;
                    currentStreak += 1;
                }

                longestStreak = Math.max(longestStreak, currentStreak);
            }
        }

        return longestStreak;
    }
}
